package com.nf.health.app.sweat.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.VolleyError;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.customview.ScrollTextView;
import com.nf.health.app.customview.SweatShowView;
import com.nf.health.app.http.Act;
import com.nf.health.app.sweat.bean.ParseDataBean;
import com.nf.health.app.sweat.bean.SweatSettingBean;
import com.nf.health.app.sweat.service.SweatServiceTwoFastBle;
import com.nf.health.app.sweat.util.SweatBluetoothUtils;
import com.nf.health.app.sweat.util.SweatConfiguration;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by he_pan on 2016/5/21.
 */
public class SweatAnalyzerActivity extends BaseActivity {

    private static final String FLAG_ADD_DATA = "flag_add_data";
    private static final int SWEAT_SET_REQUEST_CODE = 1;

    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.iv_left)
    ImageView ivLeft;
    @Bind(R.id.tv_left)
    TextView tvLeft;
    @Bind(R.id.ll_left)
    LinearLayout llLeft;
    @Bind(R.id.iv_right)
    ImageView ivRight;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.ll_right)
    LinearLayout llRight;
    @Bind(R.id.btn_history)
    Button btnHistory;
    @Bind(R.id.tv_unit)
    TextView tvUnit;
    @Bind(R.id.tv_hint)
    TextView tvHint;
    @Bind(R.id.tv_measure_date)
    TextView tvMeasureDate;
    @Bind(R.id.ll_show_data)
    LinearLayout llShowData;
    @Bind(R.id.sh_channel1)
    SweatShowView shChannel1;
    @Bind(R.id.sh_channel2)
    SweatShowView shChannel2;
    @Bind(R.id.sh_channel3)
    SweatShowView shChannel3;
    @Bind(R.id.sh_channel4)
    SweatShowView shChannel4;
    @Bind(R.id.sh_channel5)
    SweatShowView shChannel5;
    @Bind(R.id.sh_channel6)
    SweatShowView shChannel6;
    @Bind(R.id.sh_channel7)
    SweatShowView shChannel7;
    @Bind(R.id.sh_channel8)
    SweatShowView shChannel8;
    @Bind(R.id.sh_channel9)
    SweatShowView shChannel9;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.tv_channel1)
    TextView tvChannel1;
    @Bind(R.id.tv_channel2)
    TextView tvChannel2;
    @Bind(R.id.tv_channel3)
    TextView tvChannel3;
    @Bind(R.id.tv_channel4)
    TextView tvChannel4;
    @Bind(R.id.tv_channel5)
    TextView tvChannel5;
    @Bind(R.id.tv_channel6)
    TextView tvChannel6;
    @Bind(R.id.tv_channel7)
    TextView tvChannel7;
    @Bind(R.id.tv_channel8)
    TextView tvChannel8;
    @Bind(R.id.tv_channel9)
    TextView tvChannel9;
    @Bind(R.id.ll_show_chanel)
    LinearLayout llShowChanel;
    String address;
    // 蓝牙服务类
    private SweatServiceTwoFastBle mBluetoothLeService;
    private int collection_frequency = 10;//采集频率
    private ArrayList<ParseDataBean> dataList = new ArrayList<>();//存储数据,大于某个数值就上传
    private ArrayList<ParseDataBean> dataListLine = new ArrayList<>();//存储数据,用于画线,和上传池简单区分
    //存储18路数据(温湿度,各九路)
    ArrayList<ArrayList<Float>> lineData = new ArrayList<>();
    private int currentIndex = 1;//记录当前显示的类别,1温度 2湿度
    private SweatSettingBean mSweatSetBean;//记录没路数据对应部位
    private static final int READ_DATA = 1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case READ_DATA:
                    //读取数据命令
                    if (mBluetoothLeService != null) {
                        mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_READ_DATA, 10);
                        //重复读取,间隔为collection_frequency,但最少要间隔5秒
                        if (collection_frequency >= 5) {
                            removeMessages(READ_DATA);
                            sendEmptyMessageDelayed(READ_DATA, collection_frequency * 1000);
                        } else {
                            removeMessages(READ_DATA);
                            sendEmptyMessageDelayed(READ_DATA, 5 * 1000);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private ServiceConnection mServiceConnection;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_sweatanalizy);//汗液数据 layout布局
        address = PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS_ONE, "");
        ButterKnife.bind(this);
        initView();
        initListener();
        initData();
        bindLeService();
    }

    private void initView() {
        ViewUtil.setText(this, R.id.titlebar_title_tv, "汗液数据");
        titlebarRightView.setImageResource(R.drawable.ic_title_setting);
        //设置tv可以滑动
        for (int i = 0; i < llShowChanel.getChildCount(); i++) {
            View v = llShowChanel.getChildAt(i);
            if (v instanceof ScrollTextView) {
                ((ScrollTextView) v).setMovementMethod(ScrollingMovementMethod.getInstance());
            }
        }
    }

    private void initData() {
        //获得采集频率,默认10s/每次
        collection_frequency = Integer.valueOf(PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_FREQUENCY_ONE, "10"));
        for (int i = 0; i < 18; i++) {
            lineData.add(i, new ArrayList<Float>());
        }
        provider.getUserSweatSetting();
    }

    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        llLeft.setOnClickListener(this);
        llRight.setOnClickListener(this);
        btnHistory.setOnClickListener(this);
    }


    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((SweatServiceTwoFastBle.LocalBinder) service).getService();
                if (mBluetoothLeService.initialize()) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mBluetoothLeService.scanMacAndConnect(address);
                        }
                    }, 3000);
                } else {
                    tvHint.setText("初始化失败...");
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, SweatServiceTwoFastBle.class);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 所有关于蓝牙的回调都在这里
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (SweatServiceTwoFastBle.ACTION_GATT_START_SCAN_AND_CONNECT.equals(action)) {
                tvHint.setText("尝试扫描并连接...");
            } else if (SweatServiceTwoFastBle.ACTION_GATT_CONNECTED.equals(action)) {
                tvHint.setText("连接成功,尝试获取蓝牙服务...");
            } else if (SweatServiceTwoFastBle.ACTION_GATT_DISCONNECTED.equals(action)) {
                tvHint.setText("蓝牙断开 3 秒后重连...");
            } else if (SweatServiceTwoFastBle.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                //获得采样频率
                mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_SET_FREQ, 0);
                //延时发送读取数据
                mHandler.sendEmptyMessageDelayed(READ_DATA, 2000);
                tvHint.setText("蓝牙就绪");
            } else if (SweatServiceTwoFastBle.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(SweatServiceTwoFastBle.EXTRA_DATA);
                if (data == null) {
                    return;
                }
                try {
                    handleFrameData(data);
                } catch (Exception e) {
                    LogUtil.exception(e);
                }
            } else if (SweatServiceTwoFastBle.ACTION_GATT_DEVICE_NOT_FOUND.equals(action)) {
                tvHint.setText("未发现设备! 3秒后重连...");
            } else if (SweatServiceTwoFastBle.ACTION_SEND_COMMAND_FAILURE.equals(action)) {
                tvHint.setText("发送命令失败!请确认蓝牙连接正常");
            }
        }

    };

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_view://右上角弹出popupwindow
                showPop();
                break;
            case R.id.btn_history:
                ActivityUtils.showActivity(this, SweatAnalyzerHistoryTrackActivity.class);
//                mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_READ_DATA, 10);
                break;
            case R.id.ll_left:
                setSelectTitle(1);
                break;
            case R.id.ll_right:
                setSelectTitle(2);
                break;
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (FLAG_ADD_DATA.equals(actionName)) {
            showToast("阶段上传ok");
        } else if (Act.Flag.GET_SWEAT_SETTING_FLAG.equals(actionName)) {
            mSweatSetBean = (SweatSettingBean) object;
            initChannelName(mSweatSetBean);
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        if (FLAG_ADD_DATA.equals(actionName)) {
//            //上传失败,缓存正在上传的数据
//            if (uploadList.size() > 0) {
//                try {
//                    String data = SerializableUtil.list2String(uploadList);
//                    SweatBean bean = new SweatBean();
//                    bean.setData(data);
//                    MeasuredDataDao.saveSweatBean(bean);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }

    /**
     * 显示通道测量部位
     */
    private void initChannelName(SweatSettingBean mSweatSetBean) {
        //设置通道名
        tvChannel1.setText("1\n" + mSweatSetBean.getSweaturl01());
        tvChannel2.setText("2\n" + mSweatSetBean.getSweaturl02());
        tvChannel3.setText("3\n" + mSweatSetBean.getSweaturl03());
        tvChannel4.setText("4\n" + mSweatSetBean.getSweaturl04());
        tvChannel5.setText("5\n" + mSweatSetBean.getSweaturl05());
        tvChannel6.setText("6\n" + mSweatSetBean.getSweaturl06());
        tvChannel7.setText("7\n" + mSweatSetBean.getSweaturl07());
        tvChannel8.setText("8\n" + mSweatSetBean.getSweaturl08());
        tvChannel9.setText("9\n" + mSweatSetBean.getSweaturl09());
    }

    private void showPop() {
//        MenuPopupWindow pop = new MenuPopupWindow(this, PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_NAME, ""), true);
//        pop.setMyHandInputText("采集频率(" + PreferenceHelper.getString(PreferenceHelper.SWEAT_NANLYZER_FREQUENCY, "10") + "s一次)");
//        pop.setSweatSetVisible(View.VISIBLE);
//        pop.showAsDropDown(titlebarRightView);
//        pop.setOnMenuItemClickListener(new OnMyClickListener() {
//            @Override
//            public void onClick(int position, String flag) {
//                if (R.id.ll_bind_device == position) {
//                    if (PreferenceHelper.getBoolean(PreferenceHelper.SWEAT_NANLYZER_IS_BING, false)) {
//                        //TODO 解绑操作
//                        PreferenceHelper.putBoolean(PreferenceHelper.SWEAT_NANLYZER_IS_BING, false);
//                        PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_ADDRESS, "");
//                        PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_NAME, "");
//                        showToast("解绑成功");
////                        if (mBluetoothLeService != null) {
////                            mBluetoothLeService.close();
////                        }
//                        ActivityUtils.skipActivity(SweatAnalyzerActivity.this, PreSweatAnalyzerActivity.class);
//                    } else {
//
//                    }
//                } else if (R.id.tv_manual_input == position) {
//                    //TODO 采样频率
//                    showSampleFrequency();
//                } else if (R.id.tv_loadl_input == position) {
//                    ActivityUtils.showActivity(SweatAnalyzerActivity.this, MyShopStoreActivity.class);
//                } else if (R.id.tv_sweat_set == position) {//汗液测量位置设置
//                    ActivityUtils.showActivityForResult(SweatAnalyzerActivity.this, SweatSettingActivity.class, SWEAT_SET_REQUEST_CODE);
//                }
//            }
//        });
    }


    /**
     * 显示采样频率
     */
    private void showSampleFrequency() {
        View customView = View.inflate(this, R.layout.sweat_freq_edittext, null);
        final EditText et = (EditText) customView.findViewById(R.id.edit_text);
        et.setText(collection_frequency + "");
        et.setSelection(et.getText().length());
        int color = 0xbb2E86F4;
        new MaterialDialog.Builder(this)
                .titleColor(color)
                .positiveColor(color)
                .negativeColor(color)
                .title("设置采集频率:")
                .positiveText("设置")
                .negativeText("退出")
                .customView(customView, true)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        LogUtil.e("hepan频率", et.getText().toString());
                        String str = et.getText().toString().trim();
                        if (TextUtils.isEmpty(str)) {
                            return;
                        }
                        int freq = Integer.valueOf(str);
                        if (mBluetoothLeService != null) {
                            if (freq <= 0 || freq > 300) {
                                showToast("请输入正确范围1-300");
                            } else {
                                mBluetoothLeService.sendCommandToSweat(SweatConfiguration.COMMAND_TYPE_SET_FREQ, freq);
                            }
                        }
                    }
                }).onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        }).show();
    }

    /**
     * 处理帧数据
     *
     * @param data
     */

    private void handleFrameData(byte[] data) {
        //具体处理抽取,返回处理结果bean
        ParseDataBean bean = SweatBluetoothUtils.handleFrameDataOne(data);
        int type = bean.getType();
        if (SweatConfiguration.PARSE_TYPE_ERROR == type) {//数据错误
            tvHint.setText(bean.getErrorMsg());
        } else if (SweatConfiguration.PARSE_TYPE_READ_FREQ == type) {//频率数据
            tvHint.setText("当前频率:" + bean.getFreq());
            collection_frequency = Integer.valueOf(bean.getFreq());
            //保存采集频率
            PreferenceHelper.putString(PreferenceHelper.SWEAT_NANLYZER_FREQUENCY_ONE, bean.getFreq());
        } else if (SweatConfiguration.PARSE_TYPE_READ_DATA == type) {//温湿度数据
            tvHint.setText("读取中...");
            dataList.add(bean);
            dataListLine.add(bean);
            try {
                showDataList(currentIndex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据数据来显示折线图
     */
    private synchronized void showDataList(int currentIndex) {
        int BROKEN_LINE_NUM = 40;//折线图显示的数据点个数
        if (dataListLine.size() == 0) {
            return;
        }
        if (dataListLine.size() > BROKEN_LINE_NUM * 5) {
            dataListLine = new ArrayList<>(dataListLine.subList(dataListLine.size() - 40, dataList.size()));
        }
        for (int i = 0; i < 9; i++) {
            if (currentIndex == 2) {
                ((SweatShowView) llShowData.getChildAt(i)).setDataList(SweatBluetoothUtils.getHumListByChannel(dataListLine, i));
            } else {
                ((SweatShowView) llShowData.getChildAt(i)).setDataList(SweatBluetoothUtils.getTemListByChannel(dataListLine, i));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, SweatServiceTwoFastBle.makeGattUpdateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        //退出时还有未上传数据,上传
        if (dataList.size() > 0) {
//            provider.AddSweatData("2", dataList, FLAG_ADD_DATA);
        }
        if (mServiceConnection != null) {
            //做一些关闭蓝牙通道的操作
            unbindService(mServiceConnection);
        }
        mBluetoothLeService = null;
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SWEAT_SET_REQUEST_CODE && resultCode == RESULT_OK) {
            mSweatSetBean = (SweatSettingBean) data.getSerializableExtra(Constants.INTENT_EXTRA_BEAN);
            initChannelName(mSweatSetBean);
        }
    }

    /**
     * 设置头部选择ll的样式, note:太复杂,应该用radiogroup+selector或者自定义ll
     *
     * @param which
     */
    public void setSelectTitle(int which) {
        try {
            showDataList(currentIndex = which);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (which == 1) {//左边被选中,温度
            llLeft.setBackgroundColor(getResources().getColor(R.color.blue6));
            ivLeft.setImageResource(R.drawable.sweat_tem_icon_blue);
            tvLeft.setTextColor(getResources().getColor(R.color.theme_color));
            llRight.setBackgroundColor(getResources().getColor(R.color.white));
            ivRight.setImageResource(R.drawable.sweat_hum_icon_gray);
            tvRight.setTextColor(getResources().getColor(R.color.gray));
            tvUnit.setText("温度单位: ℃");
        } else if (which == 2) {//右边被选中
            llLeft.setBackgroundColor(getResources().getColor(R.color.white));
            ivLeft.setImageResource(R.drawable.sweat_tem_icon_gray);
            tvLeft.setTextColor(getResources().getColor(R.color.gray));
            llRight.setBackgroundColor(getResources().getColor(R.color.blue6));
            ivRight.setImageResource(R.drawable.sweat_hum_icon_blue);
            tvRight.setTextColor(getResources().getColor(R.color.theme_color));
            tvUnit.setText("湿度单位: g/m³");
        }
    }
}
